package com.mitgroup.dmrvs.view;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import com.mitgroup.dmrvs.adapter.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.mitgroup.dmrvs.R;
import com.mitgroup.dmrvs.utils.AppManager;
import com.mitgroup.dmrvs.utils.Utils;
import com.mitgroup.dmrvs.webservice.WSClient;

import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.trinea.android.common.util.PreferencesUtils;

public class AddOperatorActivity extends AppCompatActivity {
    private static final int MSG_UPDATE_OPERATOR = 1;
    private static final String BUNDLE_MSG_UPDATE_OPERATOR = "add_operator_msg";
    private static final String BUNDLE_MSG_UPDATE_OPERATOR_FAIL = "add_operator";
    private static final String BUNDLE_LOCAL_ERROR = "local_error";
    private static final String BUNDLE_MSG_UPDATE_OPERATOR_JUMP = "add_operator_jump";
    private Intent intent;
    /**handler对象*/
    private Handler handler;
    private ProgressDialog progressDialog;
    @BindView(R.id.btn_back)
    public Button back;
    @OnClick(R.id.btn_back)
    public void onBack(View view) {
        this.finish();
    }
    @BindView(R.id.tv_user_name)
    public TextView tvUserName;
    @BindView(R.id.iv_quit)
    public Button quit;
    @OnClick(R.id.iv_quit)
    public void onQuit(View view) {
        Utils.Exit(this);
    }

    @BindView(R.id.btn_nav01)
    public Button btnReceiveCar;
    @OnClick(R.id.btn_nav01)
    public void onReceiveCar(View view) {
        intent = new Intent(AddOperatorActivity.this,
                ReceiveCarActivity.class);
        startActivity(intent);
    }
    @BindView(R.id.btn_nav02)
    public Button btnDiagnose;
    @OnClick(R.id.btn_nav02)
    public void onDiagnose(View view) {
        intent = new Intent(AddOperatorActivity.this,
                CarDiagnoseActivity.class);
        startActivity(intent);
    }
    @BindView(R.id.btn_nav03)
    public Button btnOperatorManager;
    @OnClick(R.id.btn_nav03)
    public void onOperatorManager(View view) {
        intent = new Intent(AddOperatorActivity.this,
                OperatorManageActivity.class);
        startActivity(intent);
    }
    @BindView(R.id.et_operator)
    public EditText etOperator;
    @BindView(R.id.et_password)
    public EditText etPassword;
    @BindView(R.id.et_real_name)
    public EditText etRealName;
    @BindView(R.id.sp_province)
    public Spinner spProvince;
    @BindView(R.id.btn_add_operator)
    public Button btnAddOperator;
    @OnClick(R.id.btn_add_operator)
    public void onAddOperator(View view) {
        String  operatorStr=etOperator.getText().toString();
        String passwordStr=etPassword.getText().toString();
        String realNameStr=etRealName.getText().toString();

        if("请选择".equals(provinceStr))
        {
            Toast.makeText(AddOperatorActivity.this,"请选择省份！", Toast.LENGTH_SHORT).show();
        }

        else if(operatorStr== null ||"".equals(operatorStr))
        {
            Toast.makeText(AddOperatorActivity.this,"操作工不能为空！", Toast.LENGTH_SHORT).show();
            return;
        }
        else if(passwordStr == null ||"".equals(passwordStr))
        {
            Toast.makeText(AddOperatorActivity.this,"登录密码不能为空！", Toast.LENGTH_SHORT).show();
            return;
        }
        else
        {
            if(Utils.isNetworkAvailable(AddOperatorActivity.this)==false)
            {
                Toast.makeText(AddOperatorActivity.this,"网络尚未连接，请连接网络！", Toast.LENGTH_SHORT).show();
                if (progressDialog != null) {
                    progressDialog.dismiss();
                    progressDialog = null;
                }
                return;
            }

            //String password1=MD5.encrypt(password);
            if("1".equals(flag))
            {
                final String []key={"userName","password","province","realName","relUserId","userType","repairShopId"};
                final String []value={operatorStr,passwordStr,provinceStr,realNameStr,userId,"1",repairShopId};
                progressDialog = ProgressDialog.show(AddOperatorActivity.this,
                        getResources().getString(R.string.notice), "正在添加操作工信息...");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String rs = "";
                        Bundle bundle = new Bundle();
                        try {
                            rs = WSClient.soapGetInfo("uploadUserInfo",key,value);
                            if(rs!=null &&!"".equals(rs))
                            {

                                JSONTokener jsonTokener = new JSONTokener(rs);
                                JSONObject jsonObject = (JSONObject) jsonTokener
                                        .nextValue();
                                String status = jsonObject.getString("status");
                                String content = jsonObject.get("content").toString();
                                if("-1".equals(status))
                                {

                                    bundle.putString(BUNDLE_MSG_UPDATE_OPERATOR, "操作工已存在！");

                                }
                                else if("1".equals(status))
                                {

                                    bundle.putString(BUNDLE_MSG_UPDATE_OPERATOR_JUMP, "添加操作工成功！");

                                }
                                else {

                                    bundle.putString(BUNDLE_MSG_UPDATE_OPERATOR_FAIL, "添加操作工失败，请重试！");
                                }
                            }
                            else
                            {
                                bundle.putString(BUNDLE_LOCAL_ERROR, "访问服务器失败！");
                            }

                        }
                        catch (Exception e) {
                            System.out.print(e.getMessage());
                            bundle.putString(BUNDLE_LOCAL_ERROR, "访问服务器失败！");
                        }
                        Message msg = myHandler.obtainMessage();
                        msg.what = MSG_UPDATE_OPERATOR;
                        msg.setData(bundle);
                        myHandler.sendMessage(msg);
                    }
                }).start();
            }
            else
            {
                final String []key1={"userId","userName","oriUserName","password","province","realName","userType"};
                final String []value1={operatorId,operatorStr,userNameStr,passwordStr,provinceStr,realNameStr,"1"};
                progressDialog = ProgressDialog.show(AddOperatorActivity.this,
                        getResources().getString(R.string.notice), "正在修改操作工信息...");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String rs = "";
                        Bundle bundle = new Bundle();
                        try {
                            rs = WSClient.soapGetInfo("uploadUserInfoByUserId",key1,value1);
                            if(rs!=null &&!"".equals(rs))                            {

                                JSONTokener jsonTokener = new JSONTokener(rs);
                                JSONObject jsonObject = (JSONObject) jsonTokener
                                        .nextValue();
                                String status = jsonObject.getString("status");
                                String content = jsonObject.get("content").toString();
                                if("-1".equals(status))
                                {
                                    bundle.putString(BUNDLE_MSG_UPDATE_OPERATOR, "操作工已存在！");
                                }
                                else if("1".equals(status))
                                {
                                    bundle.putString(BUNDLE_MSG_UPDATE_OPERATOR_JUMP, "修改操作工成功！");
                                    Intent intent = new Intent(AddOperatorActivity.this,
                                            OperatorManageActivity.class);
                                    startActivity(intent);
                                }
                                else {

                                    bundle.putString(BUNDLE_MSG_UPDATE_OPERATOR_FAIL, "修改操作工失败，请重试！");
                                }
                            }
                            else
                            {
                                bundle.putString(BUNDLE_LOCAL_ERROR, "访问服务器失败！");
                            }

                        }
                        catch (Exception e) {
                            System.out.print(e.getMessage());
                            bundle.putString(BUNDLE_LOCAL_ERROR, "访问服务器失败！");
                        }
                        Message msg = myHandler.obtainMessage();
                        msg.what = MSG_UPDATE_OPERATOR;
                        msg.setData(bundle);
                        myHandler.sendMessage(msg);
                    }
                }).start();
            }
        }
    }
    public String userId;
    private List<String> data_list;
    private SpinnerAdapter spinnerAdapter;
    private String userNameStr;
    private String provinceStr;
    private String flag="";
    private String operatorId;
    private String repairShopId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_operator);

        ButterKnife.bind(this);
        initView();
    }
    private void initView() {
        AppManager.getAppManager().addActivity(this);
         userId = PreferencesUtils.getString(AddOperatorActivity.this, "userId");
        repairShopId = PreferencesUtils.getString(AddOperatorActivity.this, "repairShopId");
        String userType = PreferencesUtils.getString(AddOperatorActivity.this, "userType");
        if ("1".equals(userType)) {
            btnOperatorManager.setVisibility(View.GONE);
        }
        String userName = PreferencesUtils.getString(AddOperatorActivity.this, "userName");
        tvUserName.setText(userName);
        //数据
        data_list = new ArrayList<String>();
        data_list.add("请选择");
        data_list.add("北京");
        data_list.add("上海");
        data_list.add("天津");
        data_list.add("重庆");
        data_list.add("河北");
        data_list.add("山西");
        data_list.add("辽宁");
        data_list.add("吉林");
        data_list.add("黑龙江");
        data_list.add("江苏");
        data_list.add("浙江");
        data_list.add("安徽");
        data_list.add("福建");
        data_list.add("江西");
        data_list.add("山东");
        data_list.add("河南");
        data_list.add("湖北");
        data_list.add("湖南");
        data_list.add("广东");
        data_list.add("海南");
        data_list.add("四川");
        data_list.add("贵州");
        data_list.add("云南");
        data_list.add("陕西");
        data_list.add("甘肃");
        data_list.add("青海");
        data_list.add("广西");
        data_list.add("内蒙");
        data_list.add("宁夏");
        data_list.add("新疆");
        //适配器
        spinnerAdapter= new com.mitgroup.dmrvs.adapter.SpinnerAdapter(this,android.R.layout.simple_spinner_item, data_list);
        /* 设置样式 */
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        spProvince.setAdapter(spinnerAdapter);
        spProvince.setOnItemSelectedListener(new SpinnerSelectedListener());
        flag=getIntent().getStringExtra("flag");
        if("2".equals(flag))
        {

            operatorId= getIntent().getIntExtra("operatorId",0)+"";
            userNameStr= getIntent().getStringExtra("userName");
            etOperator.setText(userNameStr);
            String passwordStr= getIntent().getStringExtra("password");
            etPassword.setText(passwordStr);
            String realNameStr= getIntent().getStringExtra("realName");
            etRealName.setText(realNameStr);
            String provinceStr= getIntent().getStringExtra("province");
            int k= spinnerAdapter.getCount();
            for(int i=0;i<k;i++)
            {
                if(provinceStr.equals(spinnerAdapter.getItem(i).toString()))
                {
                    spProvince.setSelection(i,true);
                    break;
                }
            }
        }
    }

    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            switch (msg.what) {
                case MSG_UPDATE_OPERATOR:
                    String key = msg.getData().keySet().iterator().next();

                    if (BUNDLE_MSG_UPDATE_OPERATOR.equals(key)) {
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }
                        Toast.makeText(getApplicationContext(), msg.getData().getString(BUNDLE_MSG_UPDATE_OPERATOR), Toast.LENGTH_SHORT).show();
                     }
                    else if (BUNDLE_MSG_UPDATE_OPERATOR_FAIL.equals(key)) {
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }
                        Toast.makeText(getApplicationContext(), msg.getData().getString(BUNDLE_MSG_UPDATE_OPERATOR_FAIL), Toast.LENGTH_SHORT).show();
                    }
                    else if (msg.getData().keySet().contains(BUNDLE_MSG_UPDATE_OPERATOR_JUMP)) {
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }
                        Toast.makeText(getApplicationContext(), msg.getData().getString(BUNDLE_MSG_UPDATE_OPERATOR_JUMP), Toast.LENGTH_SHORT).show();
                        AddOperatorActivity.this.finish();

                    }
                    else if (BUNDLE_LOCAL_ERROR.equals(key)) {
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }
                        Toast.makeText(getApplicationContext(), "服务器连接失败！请重试！", Toast.LENGTH_SHORT).show();
                    }
                    break;
                default:
                    break;
            }
            removeMessages(msg.what);
        }
    };
    //使用数组形式操作
    class SpinnerSelectedListener implements AdapterView.OnItemSelectedListener {

        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
            provinceStr=data_list.get(arg2);
        }

        public void onNothingSelected(AdapterView<?> arg0) {
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppManager.getAppManager().finishActivity(this);
    }

}
